package com.ycsj.goldmedalnewconcept.activity;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.R.integer;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.ycsj.goldmedalnewconcept.bean.NoteNotify;
import com.ycsj.goldmedalnewconcept.constant.Constant;
import com.ycsj.goldmedalnewconcept.pickerview.view.TimePickerView;
import com.ycsj.goldmedalnewconcept.tips.CallAlarm;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.utils.TimeUtil;
import com.ycsj.goldmedalnewconcept.R;

import ct.be;

//新增备忘录
public class NoteActivity extends Activity {

	private Button bt_saveNote;
	private ImageView iv_back;
	// 时间选择控件
	TimePickerView pvTime;
	private String title;
	private String content;
	private AlarmManager am;;
	private Calendar c;
	private long TimeInMillis;
	private EditText et_title;
	private EditText et_note;
	private String begin_date;
	private TextView tv_startDate;
	private String notifydate;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_note);
		// 获取页面传递过来的备忘录时间,titile和内容
		begin_date = getIntent().getStringExtra("date");
		
		Log.e("time", "begin_date="+begin_date);
		title = getIntent().getStringExtra("title");
		content = getIntent().getStringExtra("content");
		notifydate = getIntent().getStringExtra("notifydate");
		
		Log.e("notice_date", "notifydate"+notifydate);
	
		initView();
		setOnListener();
		initData();
	}

	private void initView() {
		iv_back = (ImageView) findViewById(R.id.iv_back);
		bt_saveNote = (Button) findViewById(R.id.bt_saveNote);
		et_title = (EditText) findViewById(R.id.et_title);
		et_note = (EditText) findViewById(R.id.et_note);
		tv_startDate = (TextView) findViewById(R.id.tv_startDate);
		if (!TextUtils.isEmpty(title)) {
			et_title.setText(title);
		}

		if (!TextUtils.isEmpty(content)) {
			et_note.setText(content);
		}
		if (!TextUtils.isEmpty(notifydate)) {
			tv_startDate.setText(begin_date +" "+notifydate);
		}
		
	}
	
	public String getTime(Date date) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return format.format(date);
	}

	private void setOnListener() {
		am = (AlarmManager) getSystemService(ALARM_SERVICE);
		
		iv_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		

		tv_startDate.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				
				InputMethodManager imm3 = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				if (imm3 != null) {
					imm3.hideSoftInputFromWindow(getWindow().getDecorView()
							.getWindowToken(), 0);
				}
				
				
				pvTime = new TimePickerView(NoteActivity.this,
						TimePickerView.Type.ALL);// 时间选择器
				pvTime.setRange(2017,2030);
				pvTime.setTime(new Date(System.currentTimeMillis()+60*1000));
				pvTime.setCyclic(false);
				pvTime.setCancelable(true);
				pvTime.show();
				// 时间选择后回调
				pvTime.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {
				
					@Override
					public void onTimeSelect(Date date) {
						
						if(TimeUtil.isNowAfter(getTime(date))){
							tv_startDate.setText("选择提醒日期");
							Toast.makeText(NoteActivity.this, "不可选过去的时间，请重新选择", Toast.LENGTH_SHORT).show();
						}else{
							tv_startDate.setText(getTime(date));
						}
//						begindate = getTime(date);
					}
				});
			}
		 });

		bt_saveNote.setOnClickListener(new OnClickListener() {

			

			@Override
			public void onClick(View v) {
				
				InputMethodManager imm1 = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				if (imm1 != null) {
					imm1.hideSoftInputFromWindow(getWindow().getDecorView()
							.getWindowToken(), 0);
				}
				
				if("选择提醒日期".equals(tv_startDate.getText().toString())){
					Toast.makeText(NoteActivity.this, "请选择时间", Toast.LENGTH_SHORT).show();
					return;
				}
				
				try {
					TimeInMillis = TimeUtil.stringToLong(tv_startDate.getText().toString(), "yyyy-MM-dd HH:mm:ss");
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				String content = et_note.getText().toString().trim();
				String tag = et_title.getText().toString().trim();
				Date date = new Date();
				SimpleDateFormat dateFormat = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");
				String notice_date = dateFormat.format(date);
				String[] split = tv_startDate.getText().toString().split(" ");
				String[] split1 = begin_date.split("-");
				if ("".equals(content) || "".equals(tag)) {
					Toast.makeText(NoteActivity.this, "标题或内容为空！！！", 0).show();
				} else {
					Intent intent = new Intent(NoteActivity.this,
							CallAlarm.class);
					intent.putExtra("content", et_note.getText().toString());
					intent.putExtra("title", et_title.getText().toString());
					PendingIntent sender = PendingIntent.getBroadcast(
							NoteActivity.this, Integer.parseInt(split1[2]),
							intent, 0);
					
					
					am.set(AlarmManager.RTC_WAKEUP, TimeInMillis, sender);
//					Log.e("test", "TimeInMillis"+TimeInMillis);
//					am.cancel(sender);
					
					
					for (int i = 0; i < TipsActivity.mNotifyList.size(); i++) {
						if(TipsActivity.mNotifyList.get(i).equals(begin_date)){
							TipsActivity.mNotifyList.remove(i);
						}
					}
					NoteNotify mNotify = new NoteNotify();
					mNotify.am = am;
					mNotify.sender = sender;
					mNotify.date = begin_date;
					mNotify.notify = split[1];
					
					TipsActivity.mNotifyList.add(mNotify);
					
					OkHttpClient mOkHttpClient = new OkHttpClient();
					// mOkHttpClient.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
					FormEncodingBuilder builder = new FormEncodingBuilder();
					builder.add("type", "1");
					builder.add("c",
							SPUtil.getString(NoteActivity.this, "account", ""));
					builder.add("role",
							SPUtil.getString(NoteActivity.this, "role", ""));
					builder.add("content", content);
					builder.add("tag", tag);
					builder.add("mtype", "1");
					builder.add("status", "0");
					builder.add("notice_date", split[1]);
					Log.e("notice_date", split[1]);
//					builder.add("notice_date", notice_date);
//					builder.add("begin_date", tv_startDate.getText().toString());
					builder.add("begin_date", begin_date);
					Request request = new Request.Builder()
							.url(Constant.SERVER_URL + "PersonalAssistantMsg")
							.post(builder.build()).build();
					mOkHttpClient.newCall(request).enqueue(callBack);
				}
			}
		});
	}

	private void initData() {
		// TODO Auto-generated method stub

	}

	Handler handler = new Handler();
	Callback callBack = new Callback() {

		@Override
		public void onFailure(Request arg0, IOException arg1) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onResponse(Response arg0) throws IOException {
			// TODO Auto-generated method stub
			// Log.e("testtips", arg0.body().string());
			if ("{\"state\":1}".equals(arg0.body().string())) {
				handler.postDelayed(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub

						Toast.makeText(NoteActivity.this, "保存成功", 0).show();
						finish();
					}
				}, 0);
			}
		}

	};
	

	private String format(int x) {
		String s = "" + x;
		if (s.length() == 1)
			s = "0" + s;
		return s;
	}
}
